package com.chant.startFarming.controller;

import com.chant.startFarming.dto.Result;
import com.chant.startFarming.dto.TreeNode;
import com.chant.startFarming.entity.Pens;
import com.chant.startFarming.entity.Ranches;
import com.chant.startFarming.entity.Users;
import com.chant.startFarming.service.IPensService;
import com.chant.startFarming.service.IRanchesService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 牧场表，存储牧场的基本信息和状态 前端控制器
 * </p>
 *
 * @author chant
 * @since 2025-03-31
 */
@RestController
@RequestMapping("/ranches")
public class RanchesController {
    @Autowired
    private IRanchesService ranchesService;

    // 查询所有牧场
//    @GetMapping
//    public Result getAllRanches(
//            @RequestParam(defaultValue = "1") Integer pageNum,
//            @RequestParam(defaultValue = "10") Integer pageSize) {
//
//        PageHelper.startPage(pageNum, pageSize);
//        List<Ranches> ranchesList = ranchesService.list();
//        PageInfo<Ranches> pageInfo = new PageInfo<>(ranchesList);
//
//        return Result.ok(ranchesList, pageInfo.getTotal());
//    }
    // 查询所有牧场（不分页）
    @GetMapping
    public Result getAllRanches() {
        List<Ranches> ranchesList = ranchesService.list();
        return Result.ok(ranchesList);
    }

    // 根据ID查询牧场
    @GetMapping("/{id}")
    public Result getRanchById(@PathVariable Integer id) {
        Ranches ranches = ranchesService.getById(id);
        if( null != ranches ) {
            return Result.ok(ranches);
        } else {
            return Result.fail("ranches not found");
        }
    }

    // 添加牧场
    @PostMapping
    public Result addRanch(@RequestBody Ranches ranch) {
        boolean saved = ranchesService.save(ranch);
        if (saved) {
            return Result.ok();
        } else {
            return Result.fail("Failed to add ranches");
        }
    }

    // 更新牧场
    @PutMapping
    public Result updateRanch(@RequestBody Ranches ranch) {
        boolean updated = ranchesService.updateById(ranch);
        if (updated) {
            return Result.ok();
        } else {
            return Result.fail("Failed to update ranches");
        }
    }

    // 删除牧场
    @DeleteMapping("/{id}")
    public Result deleteRanch(@PathVariable Integer id) {
        boolean deleted = ranchesService.removeById(id);
        if (deleted) {
            return Result.ok();
        } else {
            return Result.fail("Failed to delete ranches");
        }
    }

    // 根据名称模糊查找和根据状态查找
    @GetMapping("/search")
    public Result searchRanches(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer ranchesStatus,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 开始分页
        PageHelper.startPage(pageNum, pageSize);

        List<Ranches> ranches = ranchesService.searchRanches(name, ranchesStatus);
        PageInfo<Ranches> pageInfo = new PageInfo<>(ranches);

        return Result.ok(ranches, pageInfo.getTotal());
    }


    @Autowired
    private IPensService pensService;
    // 获取牧场和圈舍的树形结构
    @GetMapping("/tree")
    public Result getRanchesTree() {
        List<Ranches> ranchesList = ranchesService.list();
        List<Pens> pensList = pensService.list();

        // 将圈舍数据按牧场ID分组
        Map<Integer, List<Pens>> pensByRanchId = pensList.stream()
                .collect(Collectors.groupingBy(Pens::getRanchId));

        // 构建树形结构
        List<TreeNode> treeData = ranchesList.stream()
                .map(ranch -> {
                    TreeNode ranchNode = new TreeNode();
                    ranchNode.setId(ranch.getId().toString());
                    ranchNode.setName(ranch.getName());
                    ranchNode.setParentId("0"); // 牧场的父节点为根节点

                    // 获取该牧场下的圈舍
                    List<Pens> pens = pensByRanchId.getOrDefault(ranch.getId(), Collections.emptyList());
                    List<TreeNode> children = pens.stream()
                            .map(pen -> {
                                TreeNode penNode = new TreeNode();
                                penNode.setId(pen.getId().toString());
                                penNode.setName(pen.getName());
                                penNode.setParentId(ranch.getId().toString());
                                return penNode;
                            })
                            .collect(Collectors.toList());

                    ranchNode.setChildren(children);
                    return ranchNode;
                })
                .collect(Collectors.toList());

        return Result.ok(treeData);
    }
}
